package com.yango.order.service.impl;

import com.yango.logistics.pojo.Logistics;
import com.yango.order.pojo.Order;
import com.yango.order.service.OrderService;
import com.yango.product.pojo.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Override
    public Order createOrder(Long productId, Long userId) {
        Product product=getProductById(productId);
        Logistics logistics = getLogisticsById(1L);
        Order order = new Order();
        order.setId(1L);
        BigDecimal tp=product.getPrice().multiply(new BigDecimal(product.getNum()));
        order.setTotalPrice(tp);
        order.setUserId(userId);
        order.setNickName("zhangsan");
        order.setAddress("马尾");
        order.setProductList(Arrays.asList( product));
        order.setLogisticsList(Arrays.asList(logistics));
        return order;
    }
    @Autowired
    private DiscoveryClient discoveryClient;
//    private RestTemplate restTemplate;
    private Product getProductById(Long productId){
        List<ServiceInstance> instances = discoveryClient.getInstances("yjb-service-product");
        ServiceInstance instance = instances.get(0);
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/product/"+productId;
        log.info("远程请求:{}",url);
        RestTemplate restTemplate = new RestTemplate();
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    public Logistics getLogisticsById(Long orderId){
        List<ServiceInstance> instances = discoveryClient.getInstances("yjb-service-logistics");
        ServiceInstance instance = instances.get(0);
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/logistics?orderId="+orderId;
        log.info("远程请求:{}",url);
        RestTemplate restTemplate = new RestTemplate();
        Logistics logistics = restTemplate.getForObject(url, Logistics.class);
        return logistics;
    }

}
